package ext.tianma.part.processors;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.ptc.core.components.beans.ObjectBean;
import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.forms.FormResultAction;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.tianma.bom.eco.BOMHelp;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.LWCUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.MyPartUtil;
import ext.tianma.part.imported.CusImportBOM;
import ext.tianma.part.imported.ImportConstants;
import ext.tianma.part.imported.ImportSubstituteLink;
import ext.tianma.part.imported.ImportedExcelUtil;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.method.RemoteMethodServer;
import wt.part.LineNumber;
import wt.part.Quantity;
import wt.part.QuantityUnit;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartUsageLink;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

public class ImportBOMProcessors extends DefaultObjectFormProcessor {
	private static final String CLASSNAME = CusImportBOM.class.getName();
	private static String errorMessage = "";
	private static Logger logger = LogR.getLogger(ImportBOMProcessors.class.getName());
	/** 模板路径 */
	private static String templateFolder = null;
	private static String tempFolderPath;

	static {
		try {
			templateFolder = WTProperties.getLocalProperties().getProperty("wt.home");
			tempFolderPath = templateFolder + File.separator + "codebase" + File.separator + "ext" + File.separator
					+ "tianma" + File.separator + "part" + File.separator + "config" + File.separator + "state.xlsx";
			File tempFolder = new File(tempFolderPath);
			if (!tempFolder.exists() || !tempFolder.isDirectory()) {
				tempFolder.mkdir();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public FormResult doOperation(NmCommandBean nmCommandBean, List list) throws WTException {
		errorMessage = "";
		logger.info("start import===>>>");
		FormResult formresult = new FormResult();
		String strMsg = "";
		HttpServletRequest request = nmCommandBean.getRequest();

		if (request != null) {
			String[] parameter = request.getParameterValues("fileUrl");

			if (parameter == null) {
				return formresult;
			}

			String textName = parameter[0];

			if (textName != null) {
				// 判断是否为Excel文件类型
				if (!textName.endsWith(".xls") && !textName.endsWith(".xlsx")) {
					throw new WTException("选择的文件必须是Excel格式的文件");
				}
			}
			File file = (File) request.getAttribute("fileUrl");

			if (file != null) {
				String fileNumber = file.getAbsolutePath();

				if (fileNumber != null) {
					FileInputStream fis = null;
					Workbook wb = null;
					boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
					StringBuffer strBuf = new StringBuffer();
					StringBuffer sublinkBuf = new StringBuffer();
					try {
						fis = new FileInputStream(fileNumber);
						// 根据Excel文件的格式判断文件的解释方式为03或07（解析Excel兼容性）
						if (textName.endsWith(".xls")) {
							wb = new HSSFWorkbook(fis);
						} else if (textName.endsWith(".xlsx")) {
							wb = new XSSFWorkbook(fis);
						}
						Sheet sheet = wb.getSheetAt(0);
						Sheet sheet2 = wb.getSheetAt(1);
						logger.info("===>>>" + sheet2.getSheetName());
						;
						if (sheet != null) {
							// 先校验
							StringBuffer strBuftemp = new StringBuffer();
							String Message = validateData(sheet, strBuftemp);
							Message = strBuftemp.toString();
							if (StringUtil.isNullOrEmpty(Message) || (Message.indexOf("不存在") == -1
									&& Message.indexOf("用量") == -1 && Message.indexOf("良率") == -1)) {
								// 再导入
								errorMessage = importBoms(sheet, strBuf);
								errorMessage = strBuf.toString();
							} else {
								errorMessage = Message;
							}
							System.out.println("====errorMessage:" + errorMessage);

							logger.info("start  导入==>>>" + errorMessage);
							logger.info("start  导入==>>>" + strBuf);
						}
						if (sheet2 != null) {
							logger.info("start 替换==>>>");
							String substituteInfo = "<li>替代料返回信息：</li>";
							ImportSubstituteLink.importSubstituteLink(sheet2, sublinkBuf);
							if (sublinkBuf.length() > 0) {
								substituteInfo = substituteInfo + sublinkBuf;
								errorMessage += substituteInfo;
							} else {
								errorMessage += sublinkBuf;
							}
							// errorMessage = substituteInfo + errorMessage;
							logger.info("====>>>" + strBuf);
						}
					} catch (IOException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						logger.info("Debug   logs:");
						SessionServerHelper.manager.setAccessEnforced(flag);
					}

					if (strBuf.length() > 0) {
						logger.info("Update Part Error : " + strBuf.toString());
						// throw new WTException("请根据错误信息检查导入数据");

					} else {
						logger.info("==========>>>start import sucessful<<<=============");
					}
				}
			}
		}

		return formresult;
	}

	@Override
	public FormResult setResultNextAction(FormResult paramFormResult, NmCommandBean paramNmCommandBean,
			List<ObjectBean> paramList) throws WTException {
		logger.info("start  message====>>>>" + errorMessage);
		FormResult formResult = super.setResultNextAction(paramFormResult, paramNmCommandBean, paramList);
		if (formResult.getStatus().equals(FormProcessingStatus.SUCCESS)) {
			String result = "";
			if (errorMessage.length() > 0) {
				result = errorMessage;
				logger.info("错误====—>>>" + result);
				result = result.toString();
				formResult.setStatus(FormProcessingStatus.FAILURE);
				result = "<ul >" + result + "</ul>";
				result = "document.getElementById(\"CHECK_RESULT\").innerHTML=\"" + result + "\";alert(\"检测结果已出，请查看\")";
				formResult.setNextAction(FormResultAction.JAVASCRIPT);
				formResult.setJavascript(result);
			} else {
				formResult.setNextAction(FormResultAction.REFRESH_OPENER_AND_SUBMIT_IFRAMES);
			}

		}

		return formResult;
	}

	/***
	 * 导入bom方法
	 * 
	 * @param sheet
	 *            sheet页
	 * @param strBuf
	 *            返回错误信息
	 * @return
	 * @throws Exception
	 */
	private static String importBoms(Sheet sheet, StringBuffer strBuf) throws Exception {
		String strMesg = "";
		Map<Integer, String> headMap = getHeader(sheet);
		List<String> partInfoabc = new ArrayList<String>();
		List<WTPart> checkInPartList = new ArrayList<WTPart>();
		Set<String> errorPartList = new HashSet<String>();
		Iterator<Row> rowIterator = sheet.rowIterator();
		// 父件物料
		List<String> partList = new ArrayList<String>();
		// 父物料编号----是否存在BOM结构
		Map<String, Boolean> numberflag = new HashMap<String, Boolean>();
		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		List<String> stateList = new ArrayList<String>();
		try {
			while (rowIterator.hasNext()) {
				Row row = rowIterator.next();
				logger.info("start 3======>>>" + row);
				if (row != null) {
					int rowNumber = row.getRowNum();

					int rowNumberRow = rowNumber + 1;

					logger.info("Start Process Row " + rowNumberRow);
					if (rowNumber > ImportConstants.BOM_HEADER_ROW_INDEX) {
						if (headMap != null) {
							logger.info("headMap==>>" + headMap);
							strMesg = importBoms(row, headMap, strBuf, checkInPartList, errorPartList, rowNumberRow,
									stateList, partInfoabc, partList, numberflag);
						}
					}
					logger.info("End Process Row " + rowNumberRow);
				}
			}
		} catch (Exception e) {
			logger.info("--------exception3--------");
			throw new Exception(e.getLocalizedMessage());
		} finally {
			logger.info("errorPartList size : " + errorPartList.size());
			for (String string : errorPartList) {
				logger.info("errorPartList partNumber : " + string);
			}
			checkinWTPart(checkInPartList);
			SessionServerHelper.manager.setAccessEnforced(flag);
		}

		return strMesg;
	}

	/***
	 * 导入BOM逻辑方法
	 * 
	 * @param row
	 *            excel行
	 * @param headMap
	 *            列名称map
	 * @param strBuf
	 *            错误信息
	 * @param checkInPartList
	 *            存放检出对象
	 * @param errorPartList
	 *            不存在part集合
	 * @param rowNumberRow
	 *            行号
	 * @param stateList
	 *            存放状态集合
	 * @param partInfoabc
	 *            存放A+B+C属性列集合，勇于判断是否重复
	 * 
	 *            List<String> partList 用于存放父件编号 区别是否已有BOM结构
	 * @return
	 * @throws Exception
	 */
	private static String importBoms(Row row, Map<Integer, String> headMap, StringBuffer strBuf,
			List<WTPart> checkInPartList, Set<String> errorPartList, int rowNumberRow, List<String> stateList,
			List<String> partInfoabc, List<String> partList, Map<String, Boolean> numberflag) throws Exception {
		String strMesg = "";
		// HashMap<String, String> partInfoMap = new HashMap<String, String>();
		String parentNumber = "";
		String parentView = "";
		String parentVersion = "";
		String childNumber = "";
		String lineNumbers = "";
		String lineNumber = "";
		String quantity = "";
		String Yield = "";
		String unit = "";
		WTPart parentPart = null;
		WTPartMaster childPartMaster = null;
		WTPartConfigSpec configSpec = null;
		Iterator<Cell> cellIterator = row.cellIterator();
		Hashtable hashtable = new Hashtable();
		hashtable.clear();
		int count = 10;
		while (cellIterator.hasNext()) {
			Cell cell = cellIterator.next();
			if (cell != null) {
				int columnIndex = cell.getColumnIndex();
				String head = headMap.get(columnIndex);
				if (head == null || head.trim().isEmpty()) {
					continue;
				}
				int strLineNumber = (rowNumberRow - 5) * 10;
				logger.info("strLineNumber=========>>>" + strLineNumber);
				lineNumber = String.valueOf(strLineNumber);
				if (head.equals("Parent")) {
					parentNumber = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
				}
				// else if (head.equals("Revision")) {
				// parentVersion = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
				// }
				else if (head.equals("View")) {
					parentView = ImportedExcelUtil.getCellValueAsString(cell).trim();
					logger.info("=====parentView:" + parentView);
				} else if (head.equals("Child")) {
					childNumber = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					logger.info("=====childNumber:" + childNumber);
				}
				// else if (head.equals("Line Number")) {
				// lineNumber = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
				// }
				else if (head.equals("Quantity")) {
					quantity = ImportedExcelUtil.getCellValueAsString(cell).trim();
					logger.info("=====quantity:" + quantity);
					/*
					 * double dstr = cell.getNumericCellValue(); String strqua =
					 * String.valueOf(dstr); logger.info("yongliang=======>>>"+strqua); quantity =
					 * ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					 */
				} else if (head.equals("Yield")) {
					Yield = ImportedExcelUtil.getCellValueAsString(cell).trim();
					logger.info("=====Yield:" + Yield);
					/*
					 * double dstr = cell.getNumericCellValue(); String strqua =
					 * String.valueOf(dstr); logger.info("yongliang=======>>>"+strqua); quantity =
					 * ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					 */
				} else {
					String ibavalue = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					logger.info("Debug   head:" + head);
					if (ibavalue != null && head != null) {
						if (!head.trim().isEmpty() && !ibavalue.trim().isEmpty()) {
							hashtable.put(head, ibavalue);
						}
					}
				}
			}
		}
		if (StringUtil.isNullOrEmpty(parentNumber) && StringUtil.isNullOrEmpty(parentView)
				&& StringUtil.isNullOrEmpty(childNumber) && StringUtil.isNullOrEmpty(quantity)) {
			return strMesg;
		}

		if (StringUtil.isNullOrEmpty(parentNumber)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料编号为空" + "<li>").toString();
			return strMesg;
		}
		if (StringUtil.isNullOrEmpty(parentView)) {
			logger.info("============parentView empty=========strBuf：" + strBuf.toString());
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行视图为空" + "<li>").toString();
			logger.info("============parentView empty=========strMesg:" + strMesg);
			return strMesg;
		} else {
			// 视图转大写
			parentView = parentView.toUpperCase();
		}
		if (StringUtil.isNullOrEmpty(childNumber)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行子物料编号为空" + "<li>").toString();
			return strMesg;
		}
		if (StringUtil.isNullOrEmpty(quantity)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行物料用量为空" + "<li>").toString();
			return strMesg;
		} else {
			String regEx = "[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$";

			String regx = "^((-?\\d+.?\\d*)[Ee]{1}(-?\\d+))$";// 科学计数法正则表达式
			Pattern pattern = Pattern.compile(regx);
			System.out.println("===bd1:" + quantity + "==:" + pattern.matcher(quantity).matches());
			if (pattern.matcher(quantity).matches()) {
				try {
					BigDecimal bd1 = new BigDecimal(quantity);
					quantity = bd1.toPlainString();
					System.out.println("===bd1:" + bd1.toPlainString());
				} catch (Exception e) {
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行物料用量不符合格式" + "<li>").toString();
				}
			}

			boolean rs = quantity.matches(regEx);
			if (!rs) {
				strMesg = strBuf.append("<li>第" + rowNumberRow + "行物料用量只能为正数(包括小数)" + "<li>").toString();
				return strMesg;
			}
		}
		if (StringUtil.isNullOrEmpty(Yield)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行良率为空" + "<li>").toString();
			return strMesg;
		} else {
			if (!"1".equals(Yield) && !"1.0".equals(Yield)) {
				strMesg = strBuf.append("<li>第" + rowNumberRow + "行良率不为1" + "<li>").toString();
				return strMesg;
			}
		}
		if (parentNumber.equals(childNumber)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料与子物料编号相同" + "<li>").toString();
			return strMesg;
		}

		try {

			// 设置行号
			List<String> partListNumber = new ArrayList<String>();
			partListNumber.add(parentNumber);
			/*
			 * int counts = Collections.frequency(partListNumber, parentPart); lineNumbers =
			 * String.valueOf(counts * 10);
			 */
			// parentPart = getParentPart(parentNumber, parentView, parentVersion);
			parentPart = BOMHelp.getPart(parentNumber, "", parentView);
			String partInfos = parentNumber + parentView + childNumber;

			// 验证模板数据是否重复 检查A+B+C存在重复时，则提示模板中存在重复BOM，父件料号为XXX H10除外
			if (partInfoabc.contains(partInfos) && !"H10".equalsIgnoreCase(parentView)) {
				strMesg = strBuf.append("<li>第" + rowNumberRow + "行存在重复BOM，父物料编号为" + parentNumber + "<li>").toString();
			} else {
				partInfoabc.add(partInfos);
			}
			logger.info("parentPart====>>>" + parentPart + "number===>>" + parentNumber);

			// modify by gjw
			// childPartMaster = getChildPartMaster(childNumber);
			// WTPart childpart = getParentPart(childNumber, parentView, "");
			WTPart childpart = BOMHelp.getPart(childNumber, "", parentView);
			logger.info("childPartMaster    1111111====>>>" + childPartMaster);
			if (childpart != null) {
				childPartMaster = (WTPartMaster) childpart.getMaster();
			} else {
				if (GenericUtil.getWTPart(childNumber, "") == null) {
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行子物料" + childNumber + "不存在" + "<li>").toString();
				} else {
					strMesg = strBuf
							.append("<li>第" + rowNumberRow + "行子物料" + childNumber + "不存在" + parentView + "视图" + "<li>")
							.toString();
				}
			}
			// end
			if (parentPart == null) {
				errorPartList.add(parentNumber);
				if (GenericUtil.getWTPart(parentNumber, "") == null) {
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料" + parentNumber + "不存在" + "<li>").toString();
				} else {
					strMesg = strBuf
							.append("<li>第" + rowNumberRow + "行父物料" + parentNumber + "不存在" + parentView + "视图" + "<li>")
							.toString();

				}
			}
			if (childPartMaster == null) {
				errorPartList.add(childNumber);
			}

			// 判断父+视图下的物料是否有bom结构，如果没有不允许创建
			if (parentPart != null && childPartMaster != null && childpart != null) {
				// add by gaojinwang 先判断是否已存在link关系 再根据视图确认是否需要新建link关系
				parentPart = (WTPart) GenericUtil.checkout(parentPart);
				if (!checkInPartList.contains(parentPart)) {
					checkInPartList.add(parentPart);
				}
				Map<String, WTPartUsageLink> linklist = new HashMap<String, WTPartUsageLink>();
				QueryResult groupqrq = WTPartHelper.service.getUsesWTPartMasters(parentPart);
				while (groupqrq.hasMoreElements()) {
					WTPartUsageLink puse = (WTPartUsageLink) groupqrq.nextElement();
					String number = ((WTPartMaster) puse.getRoleBObject()).getNumber();
					linklist.put(number, puse);
				}
				logger.info("========linklist:" + linklist.toString());
				logger.info("========before getMaxLineNumber lineNumbers:" + lineNumbers);
				// 取关系中最大行号+10
				lineNumbers = String.valueOf(BOMHelp.getMaxLineNumber(parentPart) + 10);
				logger.info("========after getMaxLineNumber lineNumbers:" + lineNumbers);
				// end
				// modify by gjw 20181203
				/*
				 * if (!partList.contains(parentNumber)) { configSpec = (WTPartConfigSpec)
				 * ConfigHelper.service.getConfigSpecFor((Iterated) parentPart); QueryResult qr
				 * = WTPartHelper.service.getUsesWTParts(parentPart, configSpec); if
				 * (qr.hasMoreElements()) { strMesg += strBuf.append("<li>第" + rowNumberRow +
				 * "行该物料" + parentNumber + "已存在BOM结构，请检查！") + "</li>".toString(); } }
				 * partList.add(parentNumber);
				 */

				// 用于第一次parent存在link关系 之后仍出现parent的情况
				if (numberflag.containsKey(parentNumber)) {
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行该物料" + parentNumber + "已存在BOM结构，请检查！" + "</li>")
							.toString();
					return strMesg;
				}
				// 用于判断第一次出现parent时的校验
				if (linklist.size() != 0 && !partList.contains(parentNumber)) {
					// 校验是否已有BOM结构
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行该物料" + parentNumber + "已存在BOM结构，请检查！" + "</li>")
							.toString();
					numberflag.put(parentNumber, true);
					return strMesg;
				}
				partList.add(parentNumber);
				//
				String parentstate = parentPart.getState().getState().toString();
				String parentstatezh = parentPart.getState().getState().getDisplay(Locale.CHINA);
				String childstate = childpart.getState().getState().toString();
				String childstatezh = childpart.getState().getState().getDisplay(Locale.CHINA);
				logger.info("=============child state" + childstate);
				// end by gjw

				// 判斷物料狀態是否為 正在工作、新品、量产发布、批准、试产 （ 通过xml文件配置维护）
				logger.info("parent state===>>>" + parentPart.getState().getState().toString());
				stateList = readExcel();
				logger.info("stateList====>>" + stateList);
				if (stateList.contains(parentstate) && stateList.contains(childstate)) {
					// 判斷是否存在userLink關係
					logger.info("lineNumber====>>" + lineNumbers + "====>>>part" + childPartMaster.getNumber());
					// if (needCreateWTPartUsageLink(parentPart, childPartMaster, lineNumber)) {
					if (!linklist.containsKey(childNumber)
							|| (linklist.containsKey(childNumber) && parentView.equals("H10"))) {
						logger.info("not containsKey ====>>" + linklist.containsKey(childNumber) + "===== view H10:"
								+ parentView.equals("H10"));
						/*
						 * if (!WorkflowUtil.isObjectCheckedOut(parentPart)) { parentPart = (WTPart)
						 * CoreUtil.checkoutObject(parentPart); }
						 */
						double quanty = Double.parseDouble(quantity);
						QuantityUnit qu = null;
						if (childPartMaster != null) {
							qu = childPartMaster.getDefaultUnit();
						}
						if (qu == null) {
							qu = QuantityUnit.toQuantityUnit(unit);
						}
						logger.info("======================not containsKey 111111111111=========");
						if (qu != null) {
							logger.info("======================not containsKey 222222222222222=========");
							Quantity qtity = Quantity.newQuantity(quanty, qu);
							createWTPartUsageLink(parentPart, childPartMaster, lineNumbers, qtity, hashtable, Yield);
						}
						logger.info("======================not containsKey 33333333333333=========");

					} else {
						logger.info("containsKey or H10====>>" + childNumber);
						strMesg = strBuf
								.append("<li>第" + rowNumberRow + "行该物料" + parentNumber + "已存在BOM结构，请检查！" + "</li>")
								.toString();
					}
					count = count + 10;
					logger.info("count===>>>>" + count);

				} else {
					if (stateList.contains(parentPart.getState().getState().toString())
							&& !stateList.contains(childstate)) {
						logger.info("=======1111111======");
						strMesg = strBuf.append("<li>第" + rowNumberRow + "行子物料:" + childNumber + "状态为" + childstatezh
								+ "不在可导入的状态之内！" + "</li>").toString();

					} else if (!stateList.contains(parentPart.getState().getState().toString())
							&& stateList.contains(childstate)) {
						logger.info("=======2222222======");
						strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料:" + parentNumber + "状态为" + parentstatezh
								+ "不在可导入的状态之内！" + "</li>").toString();
					} else {
						logger.info("=======3333333======");
						strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料状态为" + parentstatezh + ",子物料状态为："
								+ childstatezh + "均不在可导入的状态之内！" + "</li>").toString();
					}
				}

			}
		} catch (WTException e) {
			logger.info("--------exception4--------");
			throw new Exception(e.getLocalizedMessage());
		}
		return strMesg;

	}

	/**
	 * 检入已检出的
	 * 
	 * @param outPart
	 */
	private static void checkinWTPart(List<WTPart> outPart) {

		if (outPart != null) {
			for (int i = 0; i < outPart.size(); i++) {
				WTPart inPart = outPart.get(i);
				if (inPart != null) {
					try {
						CoreUtil.checkinObject(inPart, "导入BOM结构完成后，检入零部件。");
					} catch (WTException e) {
						e.printStackTrace();
					}
				}
			}
		}

	}

	/**
	 * 创建UsageLink方法
	 * 
	 * @param parentPart
	 * @param childPartMaster
	 * @param lineNumber
	 * @param hashtable
	 * @param Yield
	 *            良率
	 * @throws WTException
	 */
	private static void createWTPartUsageLink(WTPart parentPart, WTPartMaster childPartMaster, String lineNumber,
			Quantity quantity, Hashtable hashtable, String Yield) {
		if (parentPart == null || childPartMaster == null) {
			return;
		}
		WTPartUsageLink usageLink;
		try {
			usageLink = WTPartUsageLink.newWTPartUsageLink(parentPart, childPartMaster);
			// 设置行号
			setLineNumber(lineNumber, usageLink);

			// 设置单位数量
			setQuantity(quantity, usageLink);
			usageLink = (WTPartUsageLink) PersistenceHelper.manager.save(usageLink);
			// 设置良率
			if (!StringUtil.isNullOrEmpty(Yield)) {
				try {
					LWCUtil.setStringIBAValue(usageLink, "Yield", Yield);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			logger.info("Debug   hashtable:" + hashtable.size());
			IBAUtil.forceSetIBAValues(usageLink, hashtable);
		} catch (WTException e) {
			logger.info("ERROR  createWTPartUsageLink: parentPart," + parentPart.getNumber() + ";childPartMaster,"
					+ childPartMaster.getNumber());
			e.printStackTrace();
		}

	}

	/**
	 * 设置usageLink的单位数量
	 * 
	 * @param quantity
	 * @param usageLink
	 */
	private static void setQuantity(Quantity quantity, WTPartUsageLink usageLink) {
		if (quantity != null && !quantity.equals("")) {
			usageLink.setQuantity(quantity);
		}
	}

	/**
	 * 创建一个usageLink关系对象并且为其行号复制
	 * 
	 * @param lineNumber
	 * @param usageLink
	 * @throws WTException
	 */
	private static void setLineNumber(String lineNumber, WTPartUsageLink usageLink) throws WTException {
		if (lineNumber != null && !lineNumber.equals("")) {

			try {
				long lineNumberValue = Long.parseLong(lineNumber);
				LineNumber newLineNumber = LineNumber.newLineNumber(lineNumberValue);
				usageLink.setLineNumber(newLineNumber);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 判断usageLink关系是否存在
	 * 
	 * @param parentPart
	 * @param childPartMaster
	 * @param lineNumber
	 * @return
	 * @throws WTException
	 */
	private static boolean needCreateWTPartUsageLink(WTPart parentPart, WTPartMaster childPartMaster, String lineNumber)
			throws WTException {
		boolean result = true;

		if (parentPart == null || childPartMaster == null) {
			return result;
		}

		List<WTPartUsageLink> allLink = getAllPartUsageLink(parentPart, childPartMaster);
		Iterator<WTPartUsageLink> linkIterator = allLink.iterator();
		while (linkIterator.hasNext()) {
			WTPartUsageLink usageLink = linkIterator.next();
			String uLinNumber = getLineNumber(usageLink);
			if (uLinNumber.equals(lineNumber)) {
				result = false;
				break;
			}
		}

		return result;
	}

	/**
	 * 获取usageLink的number
	 * 
	 * @param usageLink
	 * @return
	 */
	private static String getLineNumber(WTPartUsageLink usageLink) {
		String lineNumber = "";

		if (usageLink == null) {
			return lineNumber;
		}
		LineNumber pLineNumber = usageLink.getLineNumber();
		if (pLineNumber != null) {
			lineNumber = pLineNumber.getValue() + "";
		}

		return lineNumber;
	}

	/**
	 * 获取指定父件与子件Master所有的usageLink关系对象
	 * 
	 * @param parentPart
	 * @param childPartMaster
	 * @return
	 * @throws WTException
	 */
	private static List<WTPartUsageLink> getAllPartUsageLink(WTPart parentPart, WTPartMaster childPartMaster)
			throws WTException {
		List<WTPartUsageLink> childPartUsageLinkList = new ArrayList<WTPartUsageLink>();

		List<WTPartUsageLink> allUsageLinkList = MyPartUtil.getFirstLevelUsageLink(parentPart);

		Iterator<WTPartUsageLink> allLinkIterator = allUsageLinkList.iterator();
		while (allLinkIterator.hasNext()) {
			WTPartUsageLink partUsageLink = allLinkIterator.next();
			WTPartMaster master = partUsageLink.getUses();
			if (PersistenceHelper.isEquivalent(master, childPartMaster)) {
				childPartUsageLinkList.add(partUsageLink);
			}
		}

		return childPartUsageLinkList;
	}

	/**
	 * 根据编号获取WTPartMaster
	 * 
	 * @param childNumber
	 * @return
	 * @throws WTException
	 */
	private static WTPartMaster getChildPartMaster(String childNumber) throws WTException {

		return MyPartUtil.getWTPartMasterByNumber(childNumber);
	}

	/**
	 * 根据视图,编号,版本(指定大版本)获取相应对象
	 * 
	 * @param parentNumber
	 * @param parentView
	 * @param parentVersion
	 * @return
	 */
	private static WTPart getParentPart(String parentNumber, String parentView, String parentVersion) {
		WTPart parentPart = null;
		try {

			if (!parentVersion.equals("")) {
				parentPart = MyPartUtil.getWTPartByNumViewAndVersion(parentNumber, parentView, parentVersion);
				if (parentPart == null) {
					parentPart = CoreUtil.getWTPartByNumberAndView(parentNumber, parentView);
				}

			} else if (parentVersion.equals("")) {
				parentPart = CoreUtil.getWTPartByNumberAndView(parentNumber, parentView);
			}

		} catch (WTException e) {
			e.printStackTrace();
		}

		return parentPart;
	}

	/**
	 * 获取excel表头
	 * 
	 * @param sheet
	 * @return
	 */
	private static Map<Integer, String> getHeader(Sheet sheet) {

		Map<Integer, String> headerMap = new HashMap<Integer, String>();

		Row row = sheet.getRow(ImportConstants.BOM_HEADER_ROW_INDEX);

		if (row != null) {
			Iterator<Cell> iterator = row.cellIterator();
			while (iterator.hasNext()) {
				Cell cell = iterator.next();

				String header = ImportedExcelUtil.getCellValueAsString(cell).trim();
				Integer columnIndex = cell.getColumnIndex();
				if (header != null && !header.trim().isEmpty()) {
					headerMap.put(columnIndex, header);
				}
			}
		}

		return headerMap;
	}

	public static List<String> readExcel() {
		List<String> stateList = new ArrayList<String>();
		logger.info("开始state=====>>>");
		InputStream is = null;
		Workbook wb = null;
		String str = "";
		try {
			is = new FileInputStream(tempFolderPath);
			// is = new FileInputStream("C:\\state.xlsx");
			wb = new XSSFWorkbook(is);
			Sheet sheet = wb.getSheet("state");
			Row row;
			Cell cell;

			Map<String, String> map = new HashMap<String, String>();
			// 第一行为表头，从第二行开始遍历
			for (int i = 0, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {

				if ((row = sheet.getRow(i)) != null) {
					cell = row.getCell(0);
					// double dstr = cell.getNumericCellValue();
					// logger.info("1123---->>>" + String.valueOf(dstr));
					// row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);

					str = cell.getStringCellValue();
					logger.info("1123---->>>" + cell.getStringCellValue());
					if (str != null) {
						stateList.add(str);
					}
				}
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stateList;
	}

	public static void main(String[] args) {

		readExcel();
		if (args == null || args.length != 1) {
			return;
		}

		if (!RemoteMethodServer.ServerFlag) {
			String method = "importBoms";

			try {
				logger.info("Debug   RemoteMethodServer...");
				RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, new Class[] { String.class },
						new Object[] { args[0] });
				logger.info("Debug  end RemoteMethodServer...");
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}

		} else {
			logger.info("Debug   importBoms...");
			// importBoms( args[0] ) ;
			logger.info("Debug   end importBoms...");
		}
	}

	/***
	 * 导入bom方法
	 * 
	 * @param sheet
	 *            sheet页
	 * @param strBuf
	 *            返回错误信息
	 * @return
	 * @throws Exception
	 */
	private static String validateData(Sheet sheet, StringBuffer strBuf) throws Exception {
		String strMesg = "";
		Map<Integer, String> headMap = getHeader(sheet);
		List<String> partInfoabc = new ArrayList<String>();
		List<WTPart> checkInPartList = new ArrayList<WTPart>();
		Set<String> errorPartList = new HashSet<String>();
		Iterator<Row> rowIterator = sheet.rowIterator();
		// 父件物料
		List<String> partList = new ArrayList<String>();
		// 父物料编号----是否存在BOM结构
		Map<String, Boolean> numberflag = new HashMap<String, Boolean>();
		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		List<String> stateList = new ArrayList<String>();
		try {
			while (rowIterator.hasNext()) {
				Row row = rowIterator.next();
				logger.info("start 3======>>>" + row);
				if (row != null) {
					int rowNumber = row.getRowNum();

					int rowNumberRow = rowNumber + 1;

					logger.info("Start Process Row " + rowNumberRow);
					if (rowNumber > ImportConstants.BOM_HEADER_ROW_INDEX) {
						if (headMap != null) {
							logger.info("headMap==>>" + headMap);
							strMesg = validateimportBoms(row, headMap, strBuf, errorPartList, rowNumberRow, stateList,
									partInfoabc, partList, numberflag);
						}
					}
					logger.info("End Process Row " + rowNumberRow);
				}
			}
		} catch (Exception e) {
			logger.info("--------exception3--------");
			throw new Exception(e.getLocalizedMessage());
		} finally {
			logger.info("errorPartList size : " + errorPartList.size());
			for (String string : errorPartList) {
				logger.info("errorPartList partNumber : " + string);
			}
			SessionServerHelper.manager.setAccessEnforced(flag);
		}

		return strMesg;
	}

	private static String validateimportBoms(Row row, Map<Integer, String> headMap, StringBuffer strBuf,
			Set<String> errorPartList, int rowNumberRow, List<String> stateList, List<String> partInfoabc,
			List<String> partList, Map<String, Boolean> numberflag) throws Exception {
		String strMesg = "";
		// HashMap<String, String> partInfoMap = new HashMap<String, String>();
		String parentNumber = "";
		String parentView = "";
		String parentVersion = "";
		String childNumber = "";
		String lineNumbers = "";
		String lineNumber = "";
		String quantity = "";
		String Yield = "";
		String unit = "";
		WTPart parentPart = null;
		WTPartMaster childPartMaster = null;
		WTPartConfigSpec configSpec = null;
		Iterator<Cell> cellIterator = row.cellIterator();
		Hashtable hashtable = new Hashtable();
		hashtable.clear();
		int count = 10;
		while (cellIterator.hasNext()) {
			Cell cell = cellIterator.next();
			if (cell != null) {
				int columnIndex = cell.getColumnIndex();
				String head = headMap.get(columnIndex);
				if (head == null || head.trim().isEmpty()) {
					continue;
				}
				int strLineNumber = (rowNumberRow - 5) * 10;
				logger.info("strLineNumber=========>>>" + strLineNumber);
				lineNumber = String.valueOf(strLineNumber);
				if (head.equals("Parent")) {
					parentNumber = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
				} else if (head.equals("View")) {
					parentView = ImportedExcelUtil.getCellValueAsString(cell).trim();
					logger.info("=====parentView:" + parentView);
				} else if (head.equals("Child")) {
					childNumber = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					logger.info("=====childNumber:" + childNumber);
				} else if (head.equals("Quantity")) {
					quantity = ImportedExcelUtil.getCellValueAsString(cell).trim();
					logger.info("=====quantity:" + quantity);
					System.out.println("=====quantity:" + quantity);

				} else if (head.equals("Yield")) {
					Yield = ImportedExcelUtil.getCellValueAsString(cell).trim();
					logger.info("=====Yield:" + Yield);
					System.out.println("=====Yield:" + Yield);

				} else {
					String ibavalue = ImportedExcelUtil.getCellValueAsString(cell, true).trim();
					logger.info("Debug   head:" + head);
					if (ibavalue != null && head != null) {
						if (!head.trim().isEmpty() && !ibavalue.trim().isEmpty()) {
							hashtable.put(head, ibavalue);
						}
					}
				}
			}
		}
		if (StringUtil.isNullOrEmpty(parentNumber) && StringUtil.isNullOrEmpty(parentView)
				&& StringUtil.isNullOrEmpty(childNumber) && StringUtil.isNullOrEmpty(quantity)
				&& StringUtil.isNullOrEmpty(Yield)) {
			return strMesg;
		}

		if (StringUtil.isNullOrEmpty(parentNumber)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料编号为空" + "<li>").toString();
			return strMesg;
		}
		if (StringUtil.isNullOrEmpty(parentView)) {
			logger.info("============parentView empty=========strBuf：" + strBuf.toString());
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行视图为空" + "<li>").toString();
			logger.info("============parentView empty=========strMesg:" + strMesg);
			return strMesg;
		} else {
			parentView = parentView.toUpperCase();
			View viewObj = null;
			try {
				viewObj = ViewHelper.service.getView(parentView);
			} catch (WTException e) {
				// TODO: handle exception
			}
			if (viewObj == null) {
				strMesg = strBuf.append("<li>第" + rowNumberRow + "行" + parentView + "视图不存在" + "<li>").toString();
				return strMesg;
			}
		}
		if (StringUtil.isNullOrEmpty(childNumber)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行子物料编号为空" + "<li>").toString();
			return strMesg;
		}
		if (StringUtil.isNullOrEmpty(quantity)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行物料用量为空" + "<li>").toString();
			return strMesg;
		} else {
			String regEx = "[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$";

			String regx = "^((-?\\d+.?\\d*)[Ee]{1}(-?\\d+))$";// 科学计数法正则表达式
			Pattern pattern = Pattern.compile(regx);
			System.out.println("===bd1:" + quantity + "==:" + pattern.matcher(quantity).matches());
			if (pattern.matcher(quantity).matches()) {
				try {
					BigDecimal bd1 = new BigDecimal(quantity);
					quantity = bd1.toPlainString();
					System.out.println("===bd1:" + bd1.toPlainString());
				} catch (Exception e) {
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行物料用量不符合格式" + "<li>").toString();
				}
			}

			boolean rs = quantity.matches(regEx);
			System.out.println("==quantity:" + quantity + "==rs:" + quantity.matches(regEx));
			if (!rs) {
				strMesg = strBuf.append("<li>第" + rowNumberRow + "行物料用量只能为正数(包括小数)" + "<li>").toString();
				return strMesg;
			}
		}
		if (StringUtil.isNullOrEmpty(Yield)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行良率为空" + "<li>").toString();
			return strMesg;
		} else {
			if (!"1".equals(Yield) && !"1.0".equals(Yield)) {
				strMesg = strBuf.append("<li>第" + rowNumberRow + "行良率不为1" + "<li>").toString();
				return strMesg;
			}
		}
		if (parentNumber.equals(childNumber)) {
			strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料与子物料编号相同" + "<li>").toString();
			return strMesg;
		}

		try {

			// 设置行号
			List<String> partListNumber = new ArrayList<String>();
			partListNumber.add(parentNumber);
			parentPart = BOMHelp.getPart(parentNumber, "", parentView);
			String partInfos = parentNumber + parentView + childNumber;

			// 验证模板数据是否重复 检查A+B+C存在重复时，则提示模板中存在重复BOM，父件料号为XXX H10除外
			if (partInfoabc.contains(partInfos) && !"H10".equalsIgnoreCase(parentView)) {
				strMesg = strBuf.append("<li>第" + rowNumberRow + "行存在重复BOM，父物料编号为" + parentNumber + "<li>").toString();
			} else {
				partInfoabc.add(partInfos);
			}
			logger.info("parentPart====>>>" + parentPart + "number===>>" + parentNumber);

			WTPart childpart = BOMHelp.getPart(childNumber, "", parentView);
			logger.info("childPartMaster    1111111====>>>" + childPartMaster);
			if (childpart != null) {
				childPartMaster = (WTPartMaster) childpart.getMaster();
			} else {
				if (GenericUtil.getWTPart(childNumber, "") == null) {
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行子物料" + childNumber + "不存在" + "<li>").toString();
				} else {
					strMesg = strBuf
							.append("<li>第" + rowNumberRow + "行子物料" + childNumber + "不存在" + parentView + "视图" + "<li>")
							.toString();
				}
			}
			// end
			if (parentPart == null) {
				errorPartList.add(parentNumber);
				if (GenericUtil.getWTPart(parentNumber, "") == null) {
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料" + parentNumber + "不存在" + "<li>").toString();
				} else {
					strMesg = strBuf
							.append("<li>第" + rowNumberRow + "行父物料" + parentNumber + "不存在" + parentView + "视图" + "<li>")
							.toString();

				}
			}
			if (childPartMaster == null) {
				errorPartList.add(childNumber);
			}

			// 判断父+视图下的物料是否有bom结构，如果没有不允许创建
			if (parentPart != null && childPartMaster != null && childpart != null) {
				Map<String, WTPartUsageLink> linklist = new HashMap<String, WTPartUsageLink>();
				QueryResult groupqrq = WTPartHelper.service.getUsesWTPartMasters(parentPart);
				while (groupqrq.hasMoreElements()) {
					WTPartUsageLink puse = (WTPartUsageLink) groupqrq.nextElement();
					String number = ((WTPartMaster) puse.getRoleBObject()).getNumber();
					linklist.put(number, puse);
				}
				logger.info("========linklist:" + linklist.toString());

				// 用于第一次parent存在link关系 之后仍出现parent的情况
				if (numberflag.containsKey(parentNumber)) {
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行该物料" + parentNumber + "已存在BOM结构，请检查！" + "</li>")
							.toString();
					return strMesg;
				}
				// 用于判断第一次出现parent时的校验
				if (linklist.size() != 0 && !partList.contains(parentNumber)) {
					// 校验是否已有BOM结构
					strMesg = strBuf.append("<li>第" + rowNumberRow + "行该物料" + parentNumber + "已存在BOM结构，请检查！" + "</li>")
							.toString();
					numberflag.put(parentNumber, true);
					return strMesg;
				}
				partList.add(parentNumber);
				//
				String parentstate = parentPart.getState().getState().toString();
				String parentstatezh = parentPart.getState().getState().getDisplay(Locale.CHINA);
				String childstate = childpart.getState().getState().toString();
				String childstatezh = childpart.getState().getState().getDisplay(Locale.CHINA);
				logger.info("=============child state" + childstate);
				// end by gjw

				// 判斷物料狀態是否為 正在工作、新品、量产发布、批准、试产 （ 通过xml文件配置维护）
				logger.info("parent state===>>>" + parentPart.getState().getState().toString());
				stateList = readExcel();
				logger.info("stateList====>>" + stateList);
				if (stateList.contains(parentstate) && stateList.contains(childstate)) {
					// 判斷是否存在userLink關係
					logger.info("lineNumber====>>" + lineNumbers + "====>>>part" + childPartMaster.getNumber());
					if (!linklist.containsKey(childNumber)
							|| (linklist.containsKey(childNumber) && parentView.equals("H10"))) {
						logger.info("not containsKey ====>>" + linklist.containsKey(childNumber) + "===== view H10:"
								+ parentView.equals("H10"));

					} else {
						logger.info("containsKey or H10====>>" + childNumber);
						strMesg = strBuf
								.append("<li>第" + rowNumberRow + "行该物料" + parentNumber + "已存在BOM结构，请检查！" + "</li>")
								.toString();
					}
					count = count + 10;
					logger.info("count===>>>>" + count);

				} else {
					if (stateList.contains(parentPart.getState().getState().toString())
							&& !stateList.contains(childstate)) {
						logger.info("=======1111111======");
						strMesg = strBuf.append("<li>第" + rowNumberRow + "行子物料:" + childNumber + "状态为" + childstatezh
								+ "不在可导入的状态之内！" + "</li>").toString();

					} else if (!stateList.contains(parentPart.getState().getState().toString())
							&& stateList.contains(childstate)) {
						logger.info("=======2222222======");
						strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料:" + parentNumber + "状态为" + parentstatezh
								+ "不在可导入的状态之内！" + "</li>").toString();
					} else {
						logger.info("=======3333333======");
						strMesg = strBuf.append("<li>第" + rowNumberRow + "行父物料状态为" + parentstatezh + ",子物料状态为："
								+ childstatezh + "均不在可导入的状态之内！" + "</li>").toString();
					}
				}

			}
		} catch (WTException e) {
			logger.info("--------exception4--------");
			throw new Exception(e.getLocalizedMessage());
		}
		return strMesg;

	}
}
